<template>
  <view class="page">
    <!-- 顶部车辆卡片（可选，依赖 loadInfo 返回） -->
    <view class="car-card" v-if="data_info && data_info.carlist && data_info.carlist[car_index]">
      <image class="car-img" :src="data_info.logo" mode="aspectFill"></image>
      <view class="car-text">
        <view>{{data_info.brand}}、{{data_info.carlist[car_index].name}}</view>
        <view class="sub">{{data_info.carlist[car_index].price}}</view>
        <view class="vin">{{vin}}</view>
      </view>
    </view>

    <!-- 车辆信息 -->
    <view class="section">
      <view class="section-title">车辆信息（<text class="req">*</text>为必填）</view>
      <view class="form-card">

        <!-- 上牌时间 -->
        <picker mode="date" :value="form.regDate" :start="dateStart" :end="dateEnd" @change="onDateChange">
          <view class="cell" :class="{'err': errors.regDate}" id="cell-regDate">
            <view class="label"><text class="req">*</text>上牌时间</view>
            <view class="value" :class="{'warn': errors.regDate}">{{ form.regDate || '请选择日期' }}</view>
            <text class="ic">📅</text>
          </view>
        </picker>

        <!-- 车牌 -->
        <view class="cell" :class="{'err': errors.plateNo}" id="cell-plateNo">
          <view class="label"><text class="req">*</text>车牌</view>
          <input class="ipt" type="text" v-model="form.plateNo" :disabled="disableVinPlateOnEdit" placeholder="例：闽A·12345" />
          <text class="ic">✎</text>
        </view>

        <!-- 公里数 -->
        <view class="cell" :class="{'err': errors.km}" id="cell-km">
          <view class="label"><text class="req">*</text>公里数</view>
          <input class="ipt" type="number" v-model="form.km" placeholder="请输入公里数" />
          <text class="ic">✎</text>
        </view>

        <!-- 内外色 -->
        <view class="cell" :class="{'err': errors.color}" id="cell-color">
          <view class="label"><text class="req">*</text>内外色</view>
          <input class="ipt" type="text" v-model="form.color" placeholder="例如：黑/米" />
          <text class="ic">✎</text>
        </view>

        <!-- 过户次数 -->
        <view class="cell" :class="{'err': errors.transferTimes}" id="cell-transfer">
          <view class="label"><text class="req">*</text>过户次数</view>
          <input class="ipt" type="number" v-model="form.transferTimes" placeholder="请输入次数（整数）" />
          <text class="ic">✎</text>
        </view>

        <!-- 是否运营 -->
        <picker :range="ynRange" :value="ynIndex" @change="e=>{ynIndex=e.detail.value;form.isOperate=ynRange[ynIndex];errors.isOperate=false}">
          <view class="cell" :class="{'err': errors.isOperate}" id="cell-operate">
            <view class="label"><text class="req">*</text>是否运营</view>
            <view class="value" :class="{'warn': errors.isOperate}">{{ form.isOperate || '请选择' }}</view>
            <text class="ic">▾</text>
          </view>
        </picker>

        <!-- 所在地 -->
        <view class="cell" :class="{'err': errors.city}" id="cell-city" @tap="chooseCity">
          <view class="label"><text class="req">*</text>所在地</view>
          <view class="value" :class="{'warn': errors.city}">{{ form.city || '请选择' }}</view>
          <text class="ic">▾</text>
        </view>

        <!-- 图片必传统计条 -->
        <view class="pics-stat">
          图片（必传）：已传 {{ picsUploadedCount }} / {{ picsRequiredCount }}
          <text v-if="picsLeft>0" class="pics-left">（还差 {{ picsLeft }} 张）</text>
        </view>

        <!-- 图片项（必传 + 本地预览 + 右侧图标） -->
        <view
          class="cell"
          v-for="f in photoFields"
          :key="f.key"
          :class="{'err': isPicMissing(f.key)}"
          :id="`cell-${f.key}`"
          @tap="chooseOnePic(f.key)"
        >
          <view class="label"><text class="req">*</text>{{ f.label }}</view>
          <view class="value" :class="{'warn': isPicMissing(f.key)}">{{ showPicState(f.key) }}</view>
          <image
            v-if="getPicUrl(f.key)"
            class="thumb"
            :src="getPicUrl(f.key)"
            mode="aspectFill"
            @tap.stop="previewPic(f.key)"
          />
          <text class="iconfont icon-tupian ic"></text>
        </view>
      </view>
    </view>

    <!-- 预估价格 -->
    <view class="section">
      <view class="section-title">预估价格（必填）</view>
      <view class="kv-card">
        <picker mode="selector" :range="levelRange" range-key="name" :value="levelIndex" @change="onLevelChange">
          <view class="row" :class="{'err': errors.level}" id="row-level">
            <text class="k"><text class="req">*</text>车况等级</text>
            <view class="v v-select">
              {{ levelRange[levelIndex].name }} <text class="arrow">▾</text>
            </view>
          </view>
        </picker>

        <view class="row" :class="{'err': errors.retail}" id="row-retail">
          <text class="k"><text class="req">*</text>零售价</text>
          <view class="v v-edit">
            <input class="num" type="number" v-model="price.retailMin" placeholder="最低价" />
            <text class="dash">-</text>
            <input class="num" type="number" v-model="price.retailMax" placeholder="最高价" />
            <text class="pen">✎</text>
          </view>
        </view>

        <view class="row" :class="{'err': errors.planBuy}" id="row-plan">
          <text class="k"><text class="req">*</text>计划收购价格</text>
          <view class="v v-edit">
            <input class="num" type="number" v-model="price.planBuy" placeholder="输入价格" />
            <text class="pen">✎</text>
          </view>
        </view>
      </view>
    </view>
	
	<!-- 驳回理由（样式同意见栏） -->
	<view class="section">
	  <view class="section-title">驳回理由</view>
	  <view class="op-box">
	    <textarea v-model="form.bak" placeholder="填写驳回理由（可选）" maxlength="300" auto-height disabled=""/>

	  </view>
	</view>
	
    <!-- 底部提交 -->
    <view class="bottom-btn-box" v-if="id == 0">
      <button class="submit-btn" @click="submit">提交</button>
    </view>
	<view class="bottom-btn-box" v-else-if="status == 3">
	  <button class="submit-btn" @click="submit">{{ isEdit ? '重新提交' : '提交' }}</button>
	</view>
  </view>
</template>

<script>
import common_config from '@/static/js/common.js'
var config = common_config.config
var userInfo

export default {
  data(){
    const d=new Date(), y=d.getFullYear(), m=('0'+(d.getMonth()+1)).slice(-2), day=('0'+d.getDate()).slice(-2)
    const today=`${y}-${m}-${day}`
    return{
		status:-1,
      // 模式 & 基础
      isEdit:false,
      id:0,
      disableVinPlateOnEdit:false, // 如需编辑禁改车牌可设 true
      vin:'', data_info:{carlist:[]}, car_index:-1,

      // 下拉项
      ynRange:['是','否'], ynIndex:1,

      // 表单
      form:{ regDate:'', plateNo:'', km:'', color:'', transferTimes:'', isOperate:'', city:'', licenseImgs:[] },

      // 图片（必传）
      pics:{
        license:null, front:null, front_left:null, front_right:null,
        rear:null, rear_left:null, rear_right:null,
        dash_meter:null, front_seat:null, rear_seat:null, nameplate:null
      },
      photoFields:[
        { key:'license', label:'行驶证' },
        { key:'front', label:'车身正前' },
        { key:'front_left', label:'车身左前' },
        { key:'front_right', label:'车身右前' },
        { key:'rear', label:'车身正后' },
        { key:'rear_left', label:'车身左后' },
        { key:'rear_right', label:'车身右后' },
        { key:'dash_meter', label:'仪表台（里程）' },
        { key:'front_seat', label:'前排座椅' },
        { key:'rear_seat', label:'后排座椅' },
        { key:'nameplate', label:'车身铭牌' }
      ],
      dateStart:'2000-01-01', dateEnd:today,

      // 价格
      levelRange:[{name:'优（S）',level:'S'},{name:'良（A）',level:'A'},{name:'一般（B）',level:'B'},{name:'差（C）',level:'C'}],
      levelIndex:0,
      price:{ retailMin:'', retailMax:'', planBuy:'' },

      // 错误状态
      errors:{
        regDate:false, plateNo:false, km:false, color:false, transferTimes:false, isOperate:false, city:false,
        level:false, retail:false, planBuy:false
      }
    }
  },
  computed:{
    picsRequiredCount(){ return this.photoFields.length },
    picsUploadedCount(){ return this.photoFields.filter(f=>!!this.getPicUrl(f.key)).length },
    picsLeft(){ return this.picsRequiredCount - this.picsUploadedCount }
  },
  onLoad(op){
    this.vin=op.vin||''; this.car_index=Number(op.car_index||0)
    this.id = Number(op.id || 0)
    this.isEdit = this.id > 0

    common_config.common_if_login(()=>{}, ()=>{
      userInfo=uni.getStorageSync('userInfo'); try{ userInfo=JSON.parse(userInfo) }catch(e){}
      if (this.isEdit) {
        this.loadDetail()
      } else {
        this.loadInfo()
      }
    })
  },
  methods:{
    /* 品牌卡片数据（可选） */
    loadInfo(){
      uni.request({
        url: config.request_url + '/index/pinggu/step1?token=' + (userInfo?.token||''),
        method:'POST', header:{'Content-Type':'application/x-www-form-urlencoded'},
        data:{ vin:this.vin },
        success: (res)=>{ const r=res.data||{}; if(r.code==200){ this.data_info=r.data||{carlist:[]} } }
      })
    },

    /* —— 编辑模式：加载详情 → 回填 —— */
    loadDetail(){
      uni.showLoading({title:'加载中'})
      uni.request({
        url: config.request_url + '/index/pinggu/step1_detail?token=' + (userInfo?.token||''),
        method:'POST', header:{'Content-Type':'application/x-www-form-urlencoded'},
        data:{ id:this.id },
        success: ({data})=>{
          if(Number(data.code)===200 && data.data){ this.fillFromDetail(data.data) }
          else { common_config.calert(data.msg||'加载失败') }
        },
        fail:()=>common_config.calert('网络异常'),
        complete:()=>uni.hideLoading()
      })
    },
    fillFromDetail(d){
      // 顶部卡片可继续通过 VIN 获取，也可后端直接返回，这里保留 loadInfo
      this.vin = d.vin || this.vin
      this.car_index = d.car_index || this.car_index
      this.loadInfo()

      // 表单
      this.form.regDate = d.reg_date || ''
      this.form.plateNo = d.plate_no || ''
      this.form.km = d.km!==undefined ? String(d.km) : ''
      this.form.color = d.color || ''
      this.form.transferTimes = d.transfer_times!==undefined ? String(d.transfer_times) : ''
      this.form.isOperate = d.is_operate || ''
	  this.form.bak = d.bak || ''
      this.form.city = d.city || ''
      this.form.licenseImgs = Array.isArray(d.license_imgs) ? d.license_imgs : []

      // 等级/价格
      const lv = (Array.isArray(d.levels) && d.levels[0]) ? d.levels[0] : null
      if(lv){
        const idx = this.levelRange.findIndex(x=>x.level === lv.level)
        this.levelIndex = idx>=0 ? idx : 0
        this.price.retailMin = lv.min!==undefined ? String(lv.min) : ''
        this.price.retailMax = lv.max!==undefined ? String(lv.max) : ''
        this.price.planBuy   = lv.plan!==undefined ? String(lv.plan) : ''
      }

      // 图片
      const picsMap = d.pics || {}
      for(const f of this.photoFields){
        const u = picsMap[f.key]
        this.$set(this.pics, f.key, u ? { path:'', url:this.normalizeUrl(u) } : null)
      }
	  this.status = d.status;
    },

    /* 事件处理 */
    onDateChange(e){ this.form.regDate=e.detail.value; this.errors.regDate=false },
    onLevelChange(e){ this.levelIndex=Number(e.detail.value); this.errors.level=false },
    chooseCity(){
      uni.showActionSheet({
        itemList:['福州市','厦门市','泉州市'],
        success:res=>{ this.form.city=['福州市','厦门市','泉州市'][res.tapIndex]; this.errors.city=false }
      })
    },

    /* 选择图片（本地预览） */
    async chooseOnePic(key){
      try{
        const r=await new Promise((resolve,reject)=>{ uni.chooseImage({count:1,sizeType:['compressed'],sourceType:['album','camera'],success:resolve,fail:reject}) })
        const p=r.tempFilePaths && r.tempFilePaths[0]; if(!p) return
        this.$set(this.pics, key, { path:p, url:'' })
      }catch(e){}
    },

    /* URL 规范化：相对/协议相对 → 绝对 http(s) */
    normalizeUrl(u){
      if(!u) return ''
      u = String(u).trim()
      if(/^https?:\/\//i.test(u)) return u
      if(/^\/\//.test(u)) return 'https:' + u
      const base = (config.cdn || config.request_url || '').replace(/\/+$/,'')
      if(!base) return u
      if(u[0] !== '/') u = '/' + u
      return base + u
    },

    /* 解析上传返回：兼容 {code:200, data:"https://..."} */
    parseUploadUrl(resp){
      let raw = resp && resp.data, obj
      try{ obj = typeof raw === 'string' ? JSON.parse(raw) : raw }catch(e){ obj = { code:200, data: raw } }
      if(obj && Number(obj.code)===200){
        let url = ''
        if(typeof obj.data === 'string') url = obj.data
        else if(obj.data && typeof obj.data === 'object') url = obj.data.src || obj.data.url || ''
        else url = obj.url || obj.src || ''
        return this.normalizeUrl(url)
      }
      return ''
    },

    /* 工具 */
    getPicUrl(key){ const it=this.pics[key]; return it ? (it.url || it.path) : '' },
    previewPic(key){ const url=this.getPicUrl(key); if(url) uni.previewImage({ urls:[url], current:0 }) },
    showPicState(key){
      const it=this.pics[key]
      if(!it) return '未上传'
      return it.url ? '已上传' : (it.path ? '已选择（未上传）' : '未上传')
    },
    isPicMissing(key){ return !this.getPicUrl(key) },

    /* 滚动定位到某个 #id */
    scrollToId(id){
      this.$nextTick(()=>{
        const q = uni.createSelectorQuery().in(this)
        q.select('#'+id).boundingClientRect()
        q.selectViewport().scrollOffset()
        q.exec(res=>{
          const rect = res && res[0]
          if(rect && typeof rect.top === 'number'){
            const current = (res[1] && res[1].scrollTop) || 0
            const target = current + rect.top - 80
            uni.pageScrollTo({ scrollTop: target < 0 ? 0 : target, duration: 200 })
          }
        })
      })
    },

    /* 统一上传所有必传图片（逐张） */
    async uploadAllIfNeeded(){
      const uploadUrl = config.upload_url ? config.upload_url : (config.request_url + '/index/file/upload_img')
      const map={}
      for(const k of Object.keys(this.pics)){
        const it=this.pics[k]
        const label = (this.photoFields.find(f=>f.key===k)||{}).label || '图片'
        if(!it || (!it.path && !it.url)){
          common_config.calert(`请上传【${label}】`)
          this.scrollToId('cell-'+k)
          return null
        }
        if(it.url){ // 已有服务端地址
          const norm = this.normalizeUrl(it.url)
          this.$set(this.pics,k,{...it,url:norm})
          map[k]=norm
          continue
        }
        const url=await new Promise(resolve=>{
          uni.uploadFile({
            url: uploadUrl + '?token=' + (userInfo?.token||''),
            name:'file', filePath:it.path, formData:{scene:k},
            success:(res)=>{ const finalUrl=this.parseUploadUrl(res); resolve(finalUrl || '') },
            fail:()=>resolve('')
          })
        })
        if(!url){
          common_config.calert(`【${label}】上传失败`)
          this.scrollToId('cell-'+k)
          return null
        }
        this.$set(this.pics,k,{path:it.path,url})
        map[k]=url
      }
      return map
    },

    /* 表单校验（必填/必传/价格范围） */
    validateForm(){
      const f=this.form, p=this.price
      const errs={
        regDate: !f.regDate,
        plateNo: !f.plateNo,
        km: !(f.km!=='' && /^\d+(\.\d+)?$/.test(String(f.km))),
        color: !f.color,
        transferTimes: !(f.transferTimes!=='' && /^\d+$/.test(String(f.transferTimes))),
        isOperate: !f.isOperate,
        city: !f.city,
        level: !(this.levelRange[this.levelIndex] && this.levelRange[this.levelIndex].level),
        retail: !(p.retailMin!=='' && p.retailMax!=='' && Number(p.retailMax)>=Number(p.retailMin)),
        planBuy: !(p.planBuy!=='' && Number(p.planBuy)>=0)
      }
      this.errors = Object.assign({}, this.errors, errs)

      const msgMap={
        regDate:'请选择上牌时间',
        plateNo:'请输入车牌',
        km:'请输入正确的公里数',
        color:'请输入内外色',
        transferTimes:'请输入过户次数（整数）',
        isOperate:'请选择是否运营',
        city:'请选择所在地',
        level:'请选择车况等级',
        retail:'请填写完整的零售价区间（最高价 ≥ 最低价）',
        planBuy:'请输入计划收购价格'
      }
      const idMap={
        regDate:'cell-regDate',
        plateNo:'cell-plateNo',
        km:'cell-km',
        color:'cell-color',
        transferTimes:'cell-transfer',
        isOperate:'cell-operate',
        city:'cell-city',
        level:'row-level',
        retail:'row-retail',
        planBuy:'row-plan'
      }

      for(const k of Object.keys(errs)){
        if(errs[k]){
          common_config.calert(msgMap[k] || '请完善必填项')
          this.scrollToId(idMap[k])
          return false
        }
      }

      // 图片必传检查
      for(const fItem of this.photoFields){
        if(this.isPicMissing(fItem.key)){
          common_config.calert(`请上传【${fItem.label}】`)
          this.scrollToId('cell-'+fItem.key)
          return false
        }
      }
      return true
    },

    showCondition(){
      uni.showModal({ title:'车况信息', content:'这里展示检测结果要点（可替换为你的真实数据）', showCancel:false })
    },

    /* 提交（新增/编辑） */
    async submit(){
      if(!this.validateForm()) return
      uni.showLoading({title:'提交中'})
      const picsMap = await this.uploadAllIfNeeded()
      if(!picsMap){ uni.hideLoading(); return }

      const lvl = this.levelRange[this.levelIndex]
      const payload = {
        vin:this.vin,
        car_index:this.car_index,
        reg_date:this.form.regDate,
        plate_no:this.form.plateNo,
        km:this.form.km,
        color:this.form.color,
        transfer_times:this.form.transferTimes,
        is_operate:this.form.isOperate,
        city:this.form.city,
        pics: JSON.stringify(picsMap),
        license_imgs: JSON.stringify(this.form.licenseImgs || []),
        price_levels: JSON.stringify([{
          level:lvl.level, name:lvl.name,
          min:this.price.retailMin, max:this.price.retailMax, plan:this.price.planBuy
        }])
      }
      if(this.isEdit) payload.id = this.id

      const endpoint = this.isEdit ? '/index/pinggu/step1_update' : '/index/pinggu/step1_submit'

      uni.request({
        url: config.request_url + endpoint + '?token=' + (userInfo?.token||''),
        method:'POST', header:{'Content-Type':'application/x-www-form-urlencoded'}, data:payload,
        success:(res)=>{ uni.hideLoading(); const r=res.data||{}
          if(r.code==200){
            uni.showToast({title: this.isEdit?'更新成功':'提交成功',icon:'success'})
            setTimeout(()=>uni.navigateTo({ url:'/pages/index/sub_success' }),400)
          }else{
            common_config.calert(r.msg|| (this.isEdit?'更新失败':'提交失败') )
          }
        },
        fail:()=>{ uni.hideLoading(); common_config.calert('网络异常') }
      })
    }
  }
}
</script>

<style>
/* 页面与卡片 */
.page{background:#f6f8ff;min-height:100vh;padding:32rpx 32rpx 140rpx;}
.section{background:#fff;border-radius:20rpx;padding:24rpx;margin-bottom:28rpx;box-shadow:0 4rpx 12rpx rgba(0,0,0,0.04);}
.section-title{font-size:30rpx;font-weight:600;color:#333;margin-bottom:12rpx;}
.car-card{background:#fff;border-radius:20rpx;padding:20rpx;display:flex;gap:20rpx;align-items:center;margin-bottom:28rpx;box-shadow:0 4rpx 12rpx rgba(0,0,0,0.05);}
.car-img{width:220rpx;height:130rpx;border-radius:12rpx;flex-shrink:0;}
.car-text{flex:1;font-size:28rpx;color:#333;line-height:1.6;}
.car-text .sub{color:#777;font-size:26rpx;}
.vin{font-size:26rpx;color:#888;margin-top:4rpx;}

/* 表单表格 */
.form-card{background:#fff;border:1rpx solid #e8eef6;border-radius:16rpx;overflow:hidden;}
.cell{display:flex;align-items:center;padding:22rpx 18rpx;border-bottom:1rpx solid #edf2f7;transition:background .15s,border-color .15s;}
.cell:last-child{border-bottom:none;}
.label{width:240rpx;font-size:28rpx;color:#475569;display:flex;align-items:center;gap:6rpx;}
.value{flex:1;font-size:28rpx;color:#64748b;}
.ipt{flex:1;border:none;outline:none;background:transparent;font-size:28rpx;color:#111827;}
.ic{width:44rpx;text-align:right;font-size:30rpx;color:#9aa5b1;margin-left:10rpx;}
.thumb{width:72rpx;height:72rpx;border-radius:8rpx;margin-right:12rpx;}
input::placeholder{color:#a3aab3;}

/* 必填/错误样式 */
.req{color:#ef4444;font-weight:700;}
.warn{color:#ef4444;}
.cell.err{border-left:8rpx solid #ef4444;background:#fff7f7;}
.row.err{background:#fff7f7;border-left:8rpx solid #ef4444;}

/* 图片统计条 */
.pics-stat{padding:18rpx 18rpx 0 18rpx;color:#475569;font-size:26rpx;}
.pics-left{color:#ef4444;margin-left:8rpx;}

/* 预估价格卡片 */
.kv-card{border:1rpx solid #e8eef6;border-radius:16rpx;overflow:hidden;}
.row{display:flex;align-items:center;justify-content:space-between;padding:22rpx 18rpx;border-bottom:1rpx solid #edf2f7;transition:background .15s,border-color .15s;}
.row:last-child{border-bottom:none;}
.k{font-size:28rpx;color:#475569;}
.v{display:flex;align-items:center;font-size:28rpx;color:#111827;}
.v-select{color:#111827;}
.arrow{margin-left:8rpx;font-size:24rpx;color:#8b98a5;}
.v-edit{gap:10rpx;}
.num{width:160rpx;border:none;background:transparent;font-size:28rpx;text-align:right;color:#111827;}
.dash{margin:0 6rpx;color:#8b98a5;}
.pen{margin-left:8rpx;color:#8b98a5;font-size:26rpx;}

/* 提交条 */
.bottom-btn-box{position:fixed;left:0;right:0;bottom:0;background:#fff;padding:18rpx 28rpx;box-shadow:0 -4rpx 10rpx rgba(0,0,0,0.06);}
.submit-btn{width:100%;height:90rpx;line-height:90rpx;background:#007aff;color:#fff;font-size:30rpx;border-radius:45rpx;font-weight:600;}
.submit-btn:active{opacity:.92;}
</style>
